import json

import numpy as np
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier


def getModels():
    metrics = readMetrics()
    models = dict()
    for key, metric in metrics.items():
        if metric['metricName'] == 'TPS_Per_Sec':
            service_model = models.get(metric['metricBelongTo'], dict())
            service_model[metric['metricName']] = getRTModel(np.array(metric['values']).reshape(1, -1))
            models[metric['metricBelongTo']] = service_model
        if metric['metricName'] == 'Login_Per_Sec':
            service_model = models.get(metric['metricBelongTo'], dict())
            service_model[metric['metricName']] = getECModel(np.array(metric['values']).reshape(1, -1), [1])
            models[metric['metricBelongTo']] = service_model

    print(models)


def getRTModel(data):
    model = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1)
    model.fit(data)
    return model


def getECModel(X, y):
    print(X)
    model = RandomForestClassifier(n_estimators=10, max_features='sqrt', max_depth=None,
                                   min_samples_split=2, bootstrap=True)
    model.fit(X, y)
    return model


def readMetrics():
    f = open('../data/metrics.json', 'r')
    metrics = json.load(f)
    f.close()
    return metrics


def consAnomalousService(services):
    for i in range(0, len(services)):
        if i % 3 == 0:
            services[i]['anomalous_metrics'] = ['ResponseTime', 'ErrorCount']
        elif i % 3 == 1:
            services[i]['anomalous_metrics'] = ['ResponseTime', 'ErrorCount', 'QueryPerSecond']
        elif i % 3 == 2:
            services[i]['anomalous_metrics'] = ['ResponseTime', 'QueryPerSecond']
    return services
